package com.haohan.cloud.scm.common.tools.handler;

import com.haohan.cloud.scm.common.tools.annotation.ScmJsonFilter;
import com.haohan.cloud.scm.common.tools.annotation.ScmJsonSerializer;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;

/**
 * @author dy
 * @date 2019/5/17
 */
public class JsonReturnHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        // 有自定义的 JSON 注解 就用这个Handler 来处理
        return methodParameter.hasMethodAnnotation(ScmJsonFilter.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        // 设置这个就是最终的处理类了，处理完不再去找下一个类进行处理
        modelAndViewContainer.setRequestHandled(true);

        // 获得注解并执行filter方法 最后返回
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        Annotation[] annos = methodParameter.getMethodAnnotations();
        ScmJsonSerializer jsonSerializer = new ScmJsonSerializer();
        Arrays.asList(annos).forEach(a -> {
            if (a instanceof ScmJsonFilter) {
                ScmJsonFilter json = (ScmJsonFilter) a;
                jsonSerializer.filter(json.type(), json.include(), json.filter(), json.add());
            }
        });

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String json = jsonSerializer.toJson(returnValue);
        response.getWriter().write(json);
    }
}
